package com.lqg.bookLibrary.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.myInterface.CurrentUser;
import com.lqg.bookLibrary.common.myInterface.CurrentUserPojo;
import com.lqg.bookLibrary.pojo.AvgScore;
import com.lqg.bookLibrary.pojo.Borrow;
import com.lqg.bookLibrary.pojo.Score;
import com.lqg.bookLibrary.service.IAvgScoreService;
import com.lqg.bookLibrary.service.IBorrowService;
import com.lqg.bookLibrary.service.IScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author prodigal_lqg
 * @since 2023-04-10 
 */
@RestController
@RequestMapping("/score")
@CrossOrigin
public class ScoreController {

    @Autowired
    private IScoreService scoreService;

    @Autowired
    private IAvgScoreService avgScoreService;

    @Autowired
    private IBorrowService borrowService;

    @PostMapping("/add")
    public JsonResult add(@RequestBody String post,
                          @CurrentUser CurrentUserPojo userPojo
                          ){
        Long userId = userPojo.getUserId();
        JSONObject jsonObject = JSON.parseObject(post);
        int score = (int)jsonObject.get("score");
        Long borrowId = Long.parseLong((String) jsonObject.get("borrowId"));
        Borrow one = borrowService.lambdaQuery().eq(Borrow::getBorrowId, borrowId).one();
        scoreService.save(new Score(userId,one.getBookId(), score ));
        AvgScore one1 = avgScoreService.lambdaQuery().eq(AvgScore::getBookId, one.getBookId()).one();
        avgScoreService.lambdaUpdate()
                .eq(AvgScore::getBookId, one.getBookId())
                .update(new AvgScore(one.getBookId(),(one1.getAvgScore()+score)/2));
        return JsonResult.success();
    }

}
